/** * 用例中心 接口管理 */
<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="">
        <el-input
          size="small"
          v-model="searchForm.condition"
          prefix-icon="el-icon-search"
          placeholder="请输入接口名称、地址"
        />
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="search">搜索</el-button>
        <el-button size="small" @click="reset">重置</el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button
          v-if="!treeSelected"
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="addApi"
          >新增接口</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 接口模块 -->
    <el-col :span="6" class="left-tree">
      <!--新增刷新按钮-->
      <el-button
       size="small"
       type="primary"
       icon="el-icon-refresh"
       @click="refreshTree"
       style="margin-bottom: 10px"
      >刷新</el-button>
      <module-tree
        title="接口模块"
        :treeData="parsedTreeData"
        :currentModule="searchForm.moduleId"
        @clickModule="clickModule($event)"
        @appendModule="appendModule($event)"
        @removeModule="removeModule(arguments)"
        @dragNode="dragNode(arguments)"
      />
    </el-col>
    <!--接口列表-->
    <el-col :span="18" class="right-table">
      <div
        v-if="treeSelected === 'apiSelected'"
        class="interface-edit-container"
      >
        <InterfaceEditContent :apiId="selectedApiId" />
      </div>
      <template v-else-if="treeSelected === 'caseSelected'"
        ><ApiCaseEditContent :apiCaseId="selectedApiCaseId" :apiId="selectedApiId"
      /></template>
      <template v-else>
        <el-table
          size="small"
          :data="apiListData"
          v-loading="loading"
          element-loading-text="拼命加载中"
        >
          <el-table-column prop="num" label="NO" width="60px" />
          <el-table-column prop="name" label="接口名称" min-width="180" />
          <el-table-column prop="path" label="接口地址" min-width="150" />
          <el-table-column prop="moduleName" label="所属模块" />
          <el-table-column prop="updateTime" label="更新时间" width="150" />
          <el-table-column
            fixed="right"
            align="operation"
            label="操作"
            width="150"
          >
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="editApi(scope.row)"
                >编辑</el-button
              >
              <el-button type="text" size="mini" @click="deleteApi(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <Pagination
          v-bind:child-msg="pageParam"
          @callFather="callFather"
        ></Pagination>
      </template>
    </el-col>
    <!-- 添加模块弹窗 -->
    <module-append
      :title="title"
      :show.sync="moduleVisible"
      :moduleForm="moduleForm"
      @closeDialog="closeDialog"
      @submitModule="submitModule($event)"
    />
  </div>
</template>

<script>
import Pagination from "../common/components/pagination";
import ModuleTree from "./common/module/moduleTree";
import ModuleAppend from "./common/module/moduleAppend";
import { timestampToTime } from "@/utils/util";
import SelectTree from "../common/business/selectTree";
import Autocase from "./common/case/autocase";
import { get } from "jquery";
import InterfaceEditContent from "./components/interfaceEditContent.vue";
import ApiCaseEditContent from "./components/apiCaseEditContent.vue";

export default {
  // 注册组件
  components: {
    Pagination,
    ModuleTree,
    ModuleAppend,
    SelectTree,
    Autocase,
    InterfaceEditContent,
    ApiCaseEditContent,
  },
  data() {
    return {
      loading: false,
      moduleVisible: false,
      activeTab: "header",
      moduleForm: {
        name: "",
        parentId: "",
        parentName: "",
        data: "",
      },
      title: "添加接口模块",
      searchForm: {
        page: 1,
        limit: 10,
        condition: "",
        moduleId: "",
      },
      moduleList: [], //存放当前项目中所有module的列表
      apiListData: [],
      pageParam: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      treeData: [], //  存放所有module的数据: /nore/autotest/module/list/api/的响应结果
      parsedTreeData: [], // 存储解析后的树状结构数据
      editRuleVisible: false,
      paramRuleForm: {
        apiId: null,
        header: [],
        body: [],
        query: [],
        rest: [],
        positiveAssertion: [],
        oppositeAssertion: [],
      },
      caseApiForm: {
        header: [],
        body: { type: "json", form: [], json: "", raw: "", file: [] },
        rest: [],
        query: [],
        assertion: [],
        relation: [],
        controller: [],
        method: "",
        apiName: "",
        level: "",
        path: "",
        protocol: "",
        apiDesc: "",
        caseApiDesc: "",
        domainSignName: "",
      },
      caseListData: [], // 用于存储接口用例数据
      treeSelected: null,
      selectedApiId: null,
      selectedApiCaseId: null,
    };
  },
  created() {
    // 加载
    this.$root.Bus.$emit("initBread", ["用例中心", "接口管理"]);
    this.getTree();
    this.getdata(this.searchForm);
    console.log("searchForm:" + this.searchForm); // 这应该会在控制台中打印出 searchForm 对象
  },
  methods: {
    // 刷新树数据
    refreshTree() {
      this.getTree();
    },
    selectModule(data) {
      this.uploadFileForm.moduleId = data.id;
      this.uploadFileForm.moduleName = data.label;
    },
    // 点击模块
    clickModule(data) {
      const type = data.type;
      if (type === "api") {
        this.treeSelected = "apiSelected";
        this.selectedApiId = data.id;
        this.searchForm.apiId = data.id;
        // this.getApiDetail(this.searchForm);
      } else if (type === "case") {
        this.treeSelected = "caseSelected";
        this.selectedApiCaseId = data.id;
        this.selectedApiId = null;
        this.searchForm.apiCaseId = data.id;
        // this.getCaseApiDetail(this.searchForm);
      } else {
        this.treeSelected = null;
        this.searchForm.moduleId = data.id;
        this.getdata(this.searchForm);
      }
    },
    // 添加模块
    appendModule(data) {
      if (data) {
        if (data.type === "api") {
          this.treeSelected = "caseSelected";
          this.selectedApiId = data.id;
          this.selectedApiCaseId = null;
        } else {
          this.moduleForm.parentId = data.id;
          this.moduleForm.parentName = data.label;
          this.moduleForm.data = data;
          this.moduleVisible = true;
        }
      } else {
        this.moduleForm.parentId = 0;
        this.moduleForm.parentName = "根节点";
        this.moduleForm.data = "";
        this.moduleVisible = true;
      }
    },
    // 删除模块
    removeModule(args) {
      let node = args[0];
      let data = args[1];
      if (data.type === "case") {
        let url = "/nore/autotest/caseapi/delete/" + data.id
        this.$get(url, response => {
          if (response.status === 0) {
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex((d) => d.id === data.id);
            children.splice(index, 1);
            this.$message.success("case删除成功");
          } else {
            this.$message.error("case删除失败");
          }
        })
      } else {
        if (data.children.length != 0) {
          this.$message.warning("当前模块有子模块, 无法删除");
          return;
        }
        let url = "/nore/autotest/module/deleteApi";
        this.$post(url, data, (response) => {
          if (response.status === 0) {
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex((d) => d.id === data.id);
            children.splice(index, 1);
            this.$message.success("模块删除成功");
          } else {
            this.$message.error("模块删除失败");
          }
        });
      }
    },
    // 拖拽模块
    dragNode(args) {
      let dragNode = args[0];
      let newParent = args[1];
      let url = "/nore/autotest/module/save";
      let moduleForm = dragNode.data;
      moduleForm.parentId = newParent;
      this.$post(url, moduleForm, (response) => {
        this.$message.success("更改成功");
      });
    },
    // 关闭弹框
    closeDialog() {
      this.moduleVisible = false;
    },
    // 提交模块保存
    submitModule(moduleForm) {
      moduleForm.projectId = this.$store.state.projectId;
      moduleForm.moduleType = "api_module";
      let url = "/nore/autotest/module/save";
      this.$post(url, moduleForm, (response) => {
        const newChild = response.data;
        if (moduleForm.parentId === 0) {
          this.treeData.push(newChild);
        } else {
          if (!this.moduleForm.data.children) {
            this.$set(this.moduleForm.data, "children", []);
          }
          this.moduleForm.data.children.push(newChild);
        }
        this.moduleVisible = false;
        this.moduleForm.name = "";
      });
    },
    // 获取树数据
    getTree() {
      let url =
        "/nore/autotest/module/list/api/" + this.$store.state.projectId + "/all";
      this.$get(url, (response) => {
        this.treeData = response.data;
        this.parsedTreeData = this.parseTreeData(this.treeData);
      });
    },
    parseTreeData(data) {
      // 解析数据，构建树状结构
      const parsed = data.map((item) => {
        const { children = [], apiList = [], caseApiList = [] } = item;

        // 判断item.method是否存在，如果存在则拼接method和name作为label
        const label = item.method
          ? `${item.method} ${item.name}`
          : item.name || item.caseApiName;

        const tempChild = children.concat(apiList).concat(caseApiList);

        let type = "module";
        if (item.method != null) {
          type = "api";
        }
        if (item.caseApiName != null) {
          type = "case";
        }

        return {
          id: item.id,
          label,
          type,
          children: tempChild ? this.parseTreeData(tempChild) : [],
        };
      });
      return parsed;
    },
    // 获取列表数据方法
    getdata(searchParam) {
      this.loading = true;
      let url =
        "/nore/autotest/api/list/" + searchParam.page + "/" + searchParam.limit;
      let param = {
        condition: searchParam.condition,
        moduleId: searchParam.moduleId,
        projectId: this.$store.state.projectId,
      };
      this.$post(url, param, (response) => {
        let data = response.data;
        for (let i = 0; i < data.list.length; i++) {
          data.list[i].updateTime = timestampToTime(data.list[i].updateTime);
        }
        this.apiListData = data.list;
        this.loading = false;
        // 分页赋值
        this.pageParam.currentPage = this.searchForm.page;
        this.pageParam.pageSize = this.searchForm.limit;
        this.pageParam.total = data.total;
      });
    },
    //获取接口下的接口用例
    getApiCase(searchParam) {
      this.loading = true;
      let url = "/nore/autotest/api/caseapi?apiId=" + searchParam.moduleId;
      this.$get(url, (response) => {
        this.caseListData = response.data.map((item) => ({
          name: item.name,
        }));
        this.loading = false;
      });
    },
    //获取api接口详情
    getApiDetail(searchParam) {
      this.loading = true;
      let url = "/nore/autotest/api/detail/" + searchParam.apiId;
      this.$get(url, (response) => {
        let apiDetailData = response.data;
        console.log("apiDetailData:" + JSON.stringify(apiDetailData, null, 2));
        // 处理 apiDetailData
        if (apiDetailData.header !== null) {
          apiDetailData.header = JSON.parse(apiDetailData.header);
        }
        if (apiDetailData.body !== null) {
          apiDetailData.body = JSON.parse(apiDetailData.body);
        }
        if (apiDetailData.query !== null) {
          apiDetailData.query = JSON.parse(apiDetailData.query);
        }
        this.caseApiForm.header = apiDetailData.header;
        this.caseApiForm.body = apiDetailData.body;
        this.caseApiForm.query = apiDetailData.query;
        this.caseApiForm.assertion = [];
        this.caseApiForm.relation = [];
        this.caseApiForm.controller = [];
        this.caseApiForm.apiName = apiDetailData.name;
        this.caseApiForm.method = apiDetailData.method;
        this.caseApiForm.path = apiDetailData.path;
        this.caseApiForm.apiDesc = apiDetailData.description;
        this.caseApiForm.protocol = apiDetailData.protocol;
        this.caseApiForm.domainSignName = apiDetailData.domainSign;
        this.editCaseApiVisible = true;
        // 正确引用 this.caseApiForm
        console.log(
          "caseApiForm值为:" + JSON.stringify(this.caseApiForm, null, 2)
        );
        this.loading = false;
      });
    },
    //获取caseapi接口用例详情
    getCaseApiDetail(searchParam) {
      this.loading = true;
      let url = "/nore/autotest/caseapi/detail/" + searchParam.apiCaseId;
      this.$get(url, (response) => {
        let caseApiDetailData = response.data;
        this.loading = false;
        // 处理 caseApiDetailData
        if (caseApiDetailData.header != null) {
          caseApiDetailData.header = JSON.parse(caseApiDetailData.header);
        }
        if (caseApiDetailData.body != null) {
          caseApiDetailData.body = JSON.parse(caseApiDetailData.body);
        }
        if (caseApiDetailData.query != null) {
          caseApiDetailData.query = JSON.parse(caseApiDetailData.query);
        }
        if (caseApiDetailData.assertion != null) {
          caseApiDetailData.assertion = JSON.parse(caseApiDetailData.assertion);
        }
        if (caseApiDetailData.relation != null) {
          caseApiDetailData.relation = JSON.parse(caseApiDetailData.relation);
        }
        if (caseApiDetailData.controller != null) {
          caseApiDetailData.controller = JSON.parse(
            caseApiDetailData.controller
          );
        }

        this.caseApiForm.header = caseApiDetailData.header;
        this.caseApiForm.body = caseApiDetailData.body;
        this.caseApiForm.query = caseApiDetailData.query;
        this.caseApiForm.assertion = caseApiDetailData.assertion;
        this.caseApiForm.relation = caseApiDetailData.relation;
        this.caseApiForm.controller = caseApiDetailData.controller;
        this.caseApiForm.apiName = caseApiDetailData.apiName;
        this.caseApiForm.method = caseApiDetailData.method;
        this.caseApiForm.path = caseApiDetailData.path;
        this.caseApiForm.apiDesc = caseApiDetailData.apiDesc;
        this.caseApiForm.protocol = caseApiDetailData.protocol;
        this.caseApiForm.domainSignName = caseApiDetailData.domainSignName;
        this.caseApiForm.level = caseApiDetailData.level;
        this.editCaseApiVisible = true;
      });
    },
    // 分页插件事件
    callFather(param) {
      this.searchForm.page = param.currentPage;
      this.searchForm.limit = param.pageSize;
      this.getdata(this.searchForm);
    },
    // 搜索按钮
    search() {
      this.getdata(this.searchForm);
    },
    // 重置按钮
    reset() {
      this.searchForm.condition = "";
      this.searchForm.moduleId = "";
      this.getdata(this.searchForm);
    },
    // 新增接口
    addApi() {
      this.$router.push({ path: "/caseCenter/interfaceManage/add" });
    },
    // 编辑接口
    editApi(row) {
      this.$router.push({ path: "/caseCenter/interfaceManage/edit/" + row.id });
    },
    // 编辑用例
    editCase(row) {
      this.$router.push({
        path: "/caseCenter/caseManage/apiCase/edit/" + row.id,
      });
    },
    // 删除接口
    deleteApi(row) {
      this.$confirm("确定要删除接口吗?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let url = "/nore/autotest/api/delete";
          this.$post(url, { id: row.id }, (response) => {
            this.$message.success("删除成功");
            this.getdata(this.searchForm);
          });
        })
        .catch(() => {
          this.$message.success("取消成功");
        });
    },
  },
  props: {
    domainSign: {
      type: String,
      required: true,
    },
  },
  props: {
    reqProtocol: {
      type: String,
      required: true,
    },
  },
  props: {
    apiName: {
      type: String,
      required: true,
    },
  },
  props: {
    path: {
      type: String,
      required: true,
    },
  },
  props: {
    apiLevel: {
      type: String,
      required: true,
    },
  },
  props: {
    apiDesc: {
      type: String,
      required: true,
    },
  },
};
</script>

<style scoped>
.left-tree {
  padding-right: 5px;
  border-right: 1px solid rgb(219, 219, 219);
}
.right-table {
  padding-left: 5px;
}
.api-drawer-header {
  border-bottom: 1px solid rgb(219, 219, 219);
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 20px;
}
.api-drawer-body {
  padding: 10px 20px;
}
</style>
